package com.ssm.modular.login.servlet;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;   
import org.apache.commons.logging.LogFactory;

import com.ssm.util.SessionContext;

/**
* @ClassName: OnlineListener
* @Description: TODO 登录用户在线监听
* @author ym
* @date 2017年12月21日 上午11:51:19
*/ 
public class OnlineListener extends HttpServlet implements HttpSessionAttributeListener,HttpSessionListener{
	
	public static Log log=LogFactory.getLog(OnlineListener.class);   
	private static final long serialVersionUID = 1L;
	public static HashMap<String, String> sessionMap = new HashMap<String, String>();
	private   SessionContext sessionContext= SessionContext.getInstance();    
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		  String sname=(String)event.getSession().getAttribute("sname");  
		  String sid=(String)event.getSession().getAttribute("sid");
		  if(sname!=null&&sid!=null){
			  if (sessionMap.containsKey(sname) ) {
				  for (Entry<String, String> entry : sessionMap.entrySet()) {
					  String key = entry.getKey();
					  String value = entry.getValue();
					  if (sname.equals(key)) {
						   SessionContext sessionContext=  SessionContext.getInstance();    
	                       HttpSession sess = sessionContext.getSession(value);   
	                       sess.removeAttribute("sname");  
	                       sess.invalidate();  
						  sessionMap.put(sname, sid);
					  } 
				  }
			} else {
				 sessionMap.put(sname, sid);
			}
			  for (Entry<String, String> entry : sessionMap.entrySet()) {
				  log.info("用户登录监听----现存登录用户名称="+entry.getKey()+";现存登录用户session="+entry.getValue()); 
			}
		  }
	}
	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
	        
	}
	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		
	}
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		sessionContext.AddSession(se.getSession()); 		
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		  	HttpSession session = se.getSession();    
		  	log.info("用户登录监听----sessionId="+session.getId()+"已清除"); 
	        sessionContext.DelSession(session); 
	}
	
}
